package com.andaily.domain.developer.operation;

import com.andaily.domain.developer.Backlog;
import com.andaily.domain.developer.BacklogRepository;
import com.andaily.domain.dto.developer.BacklogFormDto;
import com.andaily.web.context.BeanProvider;

/**
 * Date: 13-9-8
 *
 * @author Shengzhao Li
 */
public class BacklogFormPersister {

    private transient BacklogRepository backlogRepository = BeanProvider.getBean(BacklogRepository.class);
    private BacklogFormDto backlogFormDto;

    public BacklogFormPersister(BacklogFormDto backlogFormDto) {
        this.backlogFormDto = backlogFormDto;
    }

    public String persist() {
        if (backlogFormDto.isNewly()) {
            return createBacklog();
        } else {
            return updateBacklog();
        }
    }

    private String updateBacklog() {
        Backlog backlog = backlogRepository.findByGuid(backlogFormDto.getGuid());
        updateValues(backlog);
        backlog.saveOrUpdate();
        return backlog.guid();
    }

    private String createBacklog() {
        Backlog backlog = new Backlog();
        updateValues(backlog);
        backlog.saveOrUpdate();
        return backlog.guid();
    }

    private void updateValues(Backlog backlog) {
        backlog.updateContent(backlogFormDto.getContent())
                .updateType(backlogFormDto.getType())
                .updateEstimateTime(backlogFormDto.getEstimateTime())
                .updatePriority(backlogFormDto.getPriority());
    }
}
